package com.cy.jt;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 定义一个全局过滤器,模拟统一认证,Spring Cloud Gateway规范中,要求所有的
 * 全局过滤器必须实现GlobalFilter接口
 */
//@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {
    /**
     * 对请求进行过滤
     * @param exchange (网关层面的交换器,通过此对象获取请求,响应对象)
     * @param chain 过滤链(这个过滤链中包含0个或多个过滤器)
     * @return Mono 代表Spring WebFlux技术中的0个或一个响应序列
     */
    //http://localhost:9000/nacos/provider/echo/9000?username=admin
    @Override
    public Mono<Void> filter(ServerWebExchange exchange,
                             GatewayFilterChain chain) {
        //获取请求和响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //获取请求参数数据,并进行数据响应
        String username=
                request.getQueryParams().getFirst("username");
        if(!"admin".equals(username)){
            System.out.println("认证失败");
            //设置响应状态码
            response.setStatusCode(HttpStatus.UNAUTHORIZED);//401
            //终止请求继续传递
            return response.setComplete();
        }
        //请求链继续传递(假如用户名为admin则继续执行后续操作)
        return chain.filter(exchange);
    }
    @Override
    public int getOrder() {
        return -200;//数字越小优先级越高
    }
}